<template>
  <el-dialog
    title="发布"
    :visible.sync="visible"
    :close-on-click-modal="false"
    width="670px"
  >
    <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
      <el-form-item prop="title" :label="titleLabel">
        <el-input ref="title" v-model.trim="form.title" />
      </el-form-item>
      <el-form-item prop="sendMode" label="模式">
        <radio-options
          v-model="form.sendMode"
          :options="DictMan.items('broadcast.sendMode')"
        />
      </el-form-item>
      <el-form-item v-show="form.sendMode == 0" prop="weekTime" label="发送时间">
        <el-time-picker
          v-model="form.weekTime"
          format="HH:mm"
          value-format="HH:mm:00"
        />
      </el-form-item>
      <el-form-item v-show="form.sendMode == 0" prop="weekDay" label="重复">
        <week-enabler v-model="form.weekDay" />
      </el-form-item>
      <el-form-item prop="rangeType" label="广播范围">
        <type-select
          v-model="form.rangeType"
          :items="DictMan.items('broadcast.scope')"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item v-if="form.rangeType == 3" prop="specifiedDevs" label="设备">
        <el-input
          v-model="form.specifiedDevs"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="输入设备号，每行一个"
        />
      </el-form-item>
      <el-form-item v-if="form.broadcastType == 0" prop="type" label="内容类型">
        <type-select
          v-model="form.type"
          :items="DictMan.items('broadcast.type')"
          :clearable="false"
          @change="onTypeChange"
        />
      </el-form-item>
      <el-form-item v-if="form.type == '0' || form.type == '5'" prop="content" :label="textLabel">
        <el-input
          v-model="form.content"
          type="textarea"
          :autosize="{ minRows: 8, maxRows: 12 }"
          :maxlength="800"
          show-word-limit
          style="font-size: 14px;"
        />
      </el-form-item>
      <el-form-item v-if="form.type == '1'" prop="fileName" label="图片">
        <el-upload
          action=""
          :auto-upload="false"
          :limit="1"
          accept="image/*"
          :on-remove="() => onUploadRemove('fileName')"
          :on-change="(file) => onUploadChange('fileName', file)"
        >
          <el-button slot="trigger" icon="el-icon-upload2">选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="form.type == '2'" prop="voiceFileName" label="语音">
        <el-upload
          action=""
          :auto-upload="false"
          :limit="1"
          accept="audio/mpeg"
          :on-remove="() => onUploadRemove('voiceFileName')"
          :on-change="(file) => onUploadChange('voiceFileName', file)"
        >
          <el-button slot="trigger" icon="el-icon-upload2">选择文件</el-button>
          <span slot="tip" class="el-upload__tip"> 请上传小于5MB的MP3文件</span>
        </el-upload>
      </el-form-item>
      <el-form-item v-if="form.type == '4'" prop="linkUrl" label="链接">
        <el-input v-model.trim="form.linkUrl" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button type="primary" icon="el-icon-check" :loading="submitting" @click="onSubmit">确认</el-button>
      <el-button type="default" @click="visible = false">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import RadioOptions from '@/components/RadioOptions';
import WeekEnabler from './WeekEnabler';
import moment from 'moment';
export default {
  components: {
    RadioOptions,
    WeekEnabler
  },
  data() {
    return {
      visible: false,
      submitting: false,
      form: {
        publisher: null,
        broadcastType: null,
        title: '',
        weekTime: null,
        weekDay: null,
        sendMode: '0',
        repeatEnabled: false,
        rangeType: null,
        specifiedDevs: '',
        type: '0',
        content: '',
        linkUrl: '',
        fileName: '',
        voiceFileName: ''
      },
      formRules: {
        title: [{required: true, trigger: 'submit', message: '请输入标题'}],
        weekTime: [{
          required: true,
          validator: (rule, value, callback) => {
            if (this.form.sendMode == 0 && !value) {
              callback('请输入时间');
            } else {
              callback();
            }
          },
          trigger: 'submit'
        }],
        sendMode: [{
          required: true,
          trigger: 'submit',
          message: '请选择模式'
        }],
        rangeType: [{required: true, trigger: 'submit', message: '请选择范围'}],
        specifiedDevs: [{required: true, trigger: 'submit', message: '请输入设备编号'}],
        type: [{required: true, trigger: 'submit', message: '请选择内容类型'}],
        content: [{required: true, trigger: 'submit', message: '请输入文本'}],
        fileName: [{required: true, trigger: 'submit', message: '请上传图片'}],
        voiceFileName: [{required: true, trigger: 'submit', message: '请上传语音'}],
        linkUrl: [{required: true, trigger: 'submit', message: '请输入链接'}]
      }
    };
  },
  computed: {
    titleLabel() {
      return {0: '标题', 1: '活动主题'}[this.form.broadcastType];
    },
    textLabel() {
      return {0: '文本', 1: '活动内容'}[this.form.broadcastType];
    }
  },
  watch: {
    'form.sendMode'(mode) {
      this.form.weekDay = new Array(7).fill(0);
      this.$refs.form.clearValidate(['sendMode', 'weekTime']);
    }
  },
  methods: {
    open(broadcastType, record) {
      this.visible = true;
      this.submitting = false;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
        this.form.broadcastType = broadcastType;
        this.form.publisher = app.admin.id;
        this.$nextTick(() => {
          if (record) {
            Object.assign(this.form, {
              title: record.title,
              sendMode: record.sendMode + '',
              weekTime: record.weekTime.substring(0, 5),
              weekDay: record.sendMode == 0 ? record.weekDay.split('').map(Number) : '',
              rangeType: record.rangeType + '',
              specifiedDevs: '',
              type: record.type + '',
              content: record.content || '',
              linkUrl: record.linkUrl || '',
              fileName: '',
              voiceFileName: ''
            });
          } else {
            this.form.weekDay = new Array(7).fill(0);
            this.$refs.title.focus();
          }
        });
      });
    },
    onTypeChange(type) {
      this.form.content = '';
      this.form.fileName = '';
      this.form.voiceFileName = '';
      this.form.linkUrl = '';
    },
    onUploadRemove(field) {
      this.form[field] = null;
    },
    onUploadChange(field, file) {
      if (file.status == 'ready') {
        this.form[field] = file.raw;
      }
    },
    onSubmit() {
      this.$refs.form.validate(async (valid, errs) => {
        if (!valid) return;

        let formData = new FormData();
        for (let name in this.form) {
          if (!['repeatEnabled', 'weekDay', 'weekTime', 'specifiedDevs'].includes(name)) {
            formData.append(name, this.form[name]);
          }
        }
        formData.append('specifiedDevs', this.form.specifiedDevs.split('\n').join(','));
        formData.append('weekDay', this.form.sendMode == 0 ? this.form.weekDay.join('') : '');
        formData.append('weekTime', this.form.sendMode == 0 ? this.form.weekTime : moment().format('HH:mm'));

        this.submitting = true;
        const ret = await this.$http.post('/api/broadcastMsg/publish', formData);
        this.submitting = false;
        if (ret.success) {
          this.$message.success('发布成功');
          this.visible = false;
          this.$vnode.context.$refs.table.reloadCurrentPage();
        }
      });
    }
  }
}
</script>
<style scoped>
>>> .el-dialog__body {
  padding-right: 30px;
}
</style>